#! /usr/bin/env python
#-*- coding: UTF-8 -*-
# I use this script to cleanup and compile VHBL
# It will make a distrib and debug version for all configs in the exploit folder
# It will also throughly cleanup the entire project (*.o and *.s files, except sdk files)

import os, shutil

# pspsdk environment variables
ENV_VARS = """export PSPDEV=/usr/local/pspdev && export PSPSDK=$PSPDEV/psp/sdk && export PATH=$PATH:$PSPDEV/bin:$PSPSDK/bin"""

os.environ["PSPDEV"] = "/usr/local/pspdev"
os.environ["PSPSDK"] = os.environ["PSPDEV"]+"/psp/sdk"
os.environ["PATH"] = os.environ["PATH"]+":"+os.environ["PSPDEV"]+"/bin:"+os.environ["PSPSDK"]+"/bin"

# list of folders that can't be compiled
dont_compile = [
"mh_common",
]

def check_environment():
	"We want to make sure that we are in a valid V/HBL environment"

	# For compatibility with standard HBL, we are only gonna check for the Makefile, loader.c and tools
	if not os.path.exists("Makefile"):
		return False
	if not os.path.exists("loader.c"):
		return False
	if not os.path.exists("tools"):
		return False
	return True


# We need these folders to properly structure the builds
def make_folders():
	if not os.path.exists("builds"):
		os.mkdir("builds")
	if not os.path.exists("builds/distrib"):
		os.mkdir("builds/distrib")
	if not os.path.exists("builds/debug"):
		os.mkdir("builds/debug")

	root, folders, files = os.walk("exploits").next()
	for i in folders:
		if i not in dont_compile:
			if not os.path.exists("builds/debug/"+i):
				os.mkdir("builds/debug/"+i)
			if not os.path.exists("builds/distrib/"+i):
				os.mkdir("builds/distrib/"+i)


# way better than make clean
def recursive_clean(path, mode):
	"""Recursively cleanup the code
depending on the mode we might also want to delete H.BIN and HBL.BIN (mode 0)
or leave them alone (mode 1)"""

	root, folders, files = os.walk(path).next()

	for i in files:
		if i.endswith(".o") or i.endswith(".s") or i.endswith("~"):
			if not i.startswith("sdk") or i.endswith("~"): # we don't want to delete sdk* files
				os.remove(root+os.sep+i)
		elif (i == "H.BIN" or i == "HBL.BIN") and mode == 0:
			os.remove(root+os.sep+i)

	for i in folders:
		recursive_clean(root+os.sep+i, mode)



# for some reason I always have to export the PSPSDK environment variables
def clean():
	os.system("""make clean""")

def compile_debug(folder):
	os.system("""make FOLDER="""+folder)

def compile_distrib(folder):
	os.system("""make distrib FOLDER="""+folder)



# copy H.BIN, HBL.BIN and IMPORTS.DAT to their respective folders
def copy_files(folder, mode):
	if mode == 0: outpath = "builds/debug/"
	else: outpath = "builds/distrib/"
	
	shutil.move("H.BIN", outpath+folder)
	shutil.move("HBL.BIN", outpath+folder)
	try:
		shutil.copyfile("exploits/"+folder+"/config/IMPORTS.DAT", outpath+folder+"/IMPORTS.DAT")
	except:
		shutil.copyfile("exploits/"+folder+"/config/imports.config_66x", outpath+folder+"/IMPORTS.DAT")

def copy_debug(folder):
	copy_files(folder, 0)

def copy_distrib(folder):
	copy_files(folder, 1)



# recursively compile V/HBL for all exploit configs, both debug and distrib and copy them to their folders
def make_recursive():
	root, folders, files = os.walk("exploits").next()

	for i in folders:
		if i not in dont_compile:
			print "compiling", i, "debug"
			compile_debug(i)
			copy_debug(i)
			clean()
			print "compiling", i, "distrib"
			compile_distrib(i)
			copy_distrib(i)
			clean()


# main program, we wanna execute other functions in a certain order
def main():

	if not check_environment():
		raise SystemExit("There doesn't seem to be a valid V/HBL environment here")

	print "Creating essential folders"
	make_folders()

	print "Cleaning up"
	recursive_clean(os.getcwd(), 0)

	print "Compiling..."
	make_recursive()

	print "Cleaning up"
	recursive_clean(os.getcwd(), 1)

	print "Done"

if __name__ == "__main__":
	main()
